const validator  = require('validator');
const _          = require('lodash');
const at         = require('../common/at');
const message    = require('../common/message');
const EventProxy = require('eventproxy');
const User       = require('../proxy').User;
const Topic      = require('../proxy').Topic;
const Reply      = require('../proxy').Reply;
const config     = require('../config');
const Response = require('../common/Response');

/**
 * 添加回复
 */
exports.add = function (req, res, next) {
    let content = req.body.r_content;
    let topic_id = req.body.topic_id;
    let reply_id = req.body.reply_id;

    let str = validator.trim(String(content));
    if(str === '' || str === 'undefined') {
        let response = new Response(0, '', '回复内容不能为空！');
        return res.send(response);
    }

    let ep = EventProxy.create();

    ep.all('topic', 'reply', function () {

    });

    ep.fail(next);

    Topic.getTopicById(topic_id, ep.doneLater(function (topic) {
        if(!topic) {
            ep.unbind();
            return next();
        }

        if(topic.lock) {
            let response = new Response(0, '', '此主题已锁定！');
            return res.send(response);
        }

        // ep.emit('topic', topic);
    }));

    Reply.newAndSave(content, topic_id, req.session.user_id, reply_id, function (err, reply) {
        if(err) {
            return next(err);
        }

        // console.log(reply);
        Topic.updateLastReply(topic_id, reply_id);

        // Topic.updateLastReply(topic_id, reply_id, ep.done(function () {
        //     // ep.emit('reply_saved', reply);
        //     //发送at消息，并防止重复 at 作者
        //     // let newContent = content.replace('@' + topicAuthor.loginname + ' ', '');
        //     // at.sendMessageToMentionUsers(newContent, topic_id, req.session.user._id, reply._id);
        // }));
    });

    User.getUser({_id: req.session.user._id}, {}, function (err, user) {
        if(err) {
            return next(err);
        }
        if (!user) {
            let response = new Response(0, '', '这个用户不存在。');
            res.send(response);
            return;
        }

        user.score += 5;
        user.reply_count += 1;
        user.save();
        req.session.user = user;

    });

    let response = new Response(1, '', '评论成功');

    res.send(response);
};

/**
 * 修改回复
 */
exports.update = function (req, res, next) {
    let edit_id = req.body.edit_id;
    let content = req.body.re_t_content;

    Reply.getReplyById(edit_id, function (err, reply) {
        if(err) {
            return next(err)
        }
        if(!reply) {
            let response = new Response(0, '', '此回复不存在或已被删除');
            res.json(response);
        }

        if(reply.reply_id.toString() === req.session.user._id.toString() || req.session.user.is_admin) {
            if(content.trim().length > 0) {
                reply.content = content;
                reply.update_at = new Date();
                reply.save(function (err) {
                    if(err) {
                        return next(err);
                    }
                    let response = new Response(1, '', '重新编辑成功。');
                    res.json(response);
                })
            } else {
                let response = new Response(0, '', '回复的字数太少。');
                res.json(response);
            }
        } else {
            let response = new Response(0, '', '对不起，你不能编辑此回复。');
            res.json(response);
        }
    })
};

/**
 * 删除回复信息
 */
exports.delete = function (req, res, next) {
    let reply_id = req.body.reply_id;
    Reply.getReplyById(reply_id, function (err, reply) {
        if(err) {
            return next(err);
        }
        if(!reply) {
            let response = new Response(0, '', '没有此条回复');
            res.json(response);
        }

        if(reply.reply_id.toString() === req.session.user._id || req.session.user.is_admin) {
            reply.deleted = true;
            reply.save();

            let response = new Response(1, '', '删除成功。');
            res.json(response);

            Topic.reduceCount(reply.topic_id, _.noop);// 更新主题的回复次数:last_reply, 并返回最新的一条回复
            User.getUser({_id: req.session.user._id}, {}, function (err, user) {
                if(err) {
                    return next(err);
                }
                if (!user) {
                    let response = new Response(0, '', '这个用户不存在。');
                    res.send(response);
                    return;
                }
                if(user.reply_count > 0) {
                    user.score -= 5;
                    user.reply_count -= 1;
                }
                user.save();
                req.session.user = user;
            });
        }

    })
};
